package com.bds.btcdc.web.service;

import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.api.TradeService;
import com.bds.btcdc.api.model.OrderInfo;
import com.bds.btcdc.api.model.OrderResponse;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.web.model.record.OrderRecord;
import com.bds.btcdc.api.model.Order;
import com.bds.btcdc.web.utils.Const;
import com.bds.btcdc.web.utils.OrderConst;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.nutz.lang.random.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: kevin
 * @date: 2018/5/11
 * @description:
 */
@Service
public class ITradeService {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private NutDao dao;
    @Resource
    private TradeService tradeService;
    @Resource
    private OrderService orderService;
    /**
     *  下单，同时记录到数据库
     */
    public Result makeOrder(Order order){
        Result rst=new Result();
        Date time=new Date();
        try {
            Result node_rst = tradeService.makeOrder(order);
            int status;
            String api_id="";
            OrderResponse response=(OrderResponse)node_rst.getData();
            if (node_rst.getCode()==200){
                status=OrderConst.SUC;
                rst.setResult(Const.SUC,"下单成功");
                api_id=response.getOrder_id();
            }else{
                status=OrderConst.FAIL;
                String msg=node_rst.getMsg();
                rst.setResult(Const.SUC,"下单失败:"+msg);
            }
            //存储交易记录
            OrderRecord record=new OrderRecord();
            record.setCreate_time(time);
            record.setExchange(order.getExchange());
            record.setNum(order.getNum());
            record.setSymbol(order.getSymbol());
            record.setUser_id(order.getUserId());
            record.setPrice(order.getPrice());
            record.setType(order.getType());
            record.setStatus(status);
            record.setApi_id(api_id);
            record.setOrder_no(orderService.getOrderNo(OrderConst.XH));
            try {
                dao.fastInsert(record);
            } catch (Exception e) {
                e.printStackTrace();
                rst.setResult(Const.FAIL,"交易保存失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            rst.setResult(Const.FAIL,"下单失败");
        }
        return rst;
    }

    public List<OrderRecord> getTradeRecord(Long user_id) {
        return dao.query(OrderRecord.class,Cnd.where("user_id","=",user_id).orderBy("create_time","desc"));
    }

    /**
     * 刷新订单状态
     * @param user_id
     * @return
     */
    public Result refreshRecordStatus(Long user_id) {
        //刷新状态为1、4的订单信息
        List<OrderRecord> list=dao.query(OrderRecord.class,Cnd.where("status","in","1,4").and("user_id","=",user_id)
        .and("exchange","=","HUOBI"));

        List<String> id_list=new ArrayList<>();
        for (OrderRecord r:list) {
            id_list.add(r.getOrder_no());
        }
        //发送订单id集合
        Result rst=tradeService.getOrders(user_id,id_list);
//        logger.info("刷新订单 >>> "+JSONObjecoJSONString(rst));

        Result return_rst=new Result();
        //拿到结果后，更新订单记录表
        if(rst.getCode()==Const.SUC){
            //rst里包装了一个Result集合，表示每个订单的查询结果
            List<Result> orders_rst=(List<Result>)rst.getData();
            for (int i = 0; i < orders_rst.size(); i++) {
                if (orders_rst.get(i).getCode()!=Const.SUC){
                    return_rst.setResult(Const.WARN,"部分刷新失败");
                    continue;
                }
                OrderInfo info=(OrderInfo)orders_rst.get(i).getData();
                Double amount=Double.valueOf(info.getAmount());//已成交数量
                String exchange=info.getExchange();
                String api_id=info.getApi_id();
                OrderRecord record=new OrderRecord(exchange,api_id);
                //取出库中对应记录
                OrderRecord _record = list.get(list.lastIndexOf(record));
                int status;
                if (amount==0){
                    status=OrderConst.SUC;
                }else if (amount.equals(_record.getNum())){
                    status=OrderConst.FINISH;
                }else{
                    status=OrderConst.PART_FINISH;
                }
                try {
                    dao.update(OrderRecord.class,Chain.make("status",status).add("finish_num",amount)
                            .add("finish_time",new Date(Long.valueOf(info.getFinish_time()))),Cnd.where("order_no","=",_record.getOrder_no()));
                } catch (Exception e) {
                    e.printStackTrace();
                    return_rst.setCode(Const.WARN);//部分订单刷新失败
                    continue;
                }
            }
        }else {
            return_rst.setResult(Const.FAIL,"刷新失败");
            return return_rst;
        }

        try {
            if (return_rst.getCode()!=Const.WARN){
                return_rst.setResult(Const.SUC,"刷新成功");
            }
        } catch (NullPointerException e) {
            return_rst.setResult(Const.SUC,"刷新成功");
        }

        return return_rst;
    }
}
